
# vip_system_tkinter.py

import tkinter as tk
from tkinter import ttk, messagebox
import sqlite3
from datetime import datetime

# Initialize DB
conn = sqlite3.connect("vip_data.db")
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    phone TEXT UNIQUE,
    balance REAL DEFAULT 0.0,
    total_recharge REAL DEFAULT 0.0
)''')
cursor.execute('''CREATE TABLE IF NOT EXISTS records (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    phone TEXT,
    type TEXT,
    amount REAL,
    date TEXT
)''')
conn.commit()
conn.close()

class VIPApp:
    def __init__(self, root):
        self.root = root
        self.root.title("理发店VIP管理系统")
        self.root.geometry("800x600")
        self.login_window()

    def login_window(self):
        for widget in self.root.winfo_children():
            widget.destroy()
        frame = tk.Frame(self.root)
        frame.pack(expand=True)
        tk.Label(frame, text="管理员登录", font=("Arial", 18)).pack(pady=10)
        tk.Label(frame, text="用户名").pack()
        self.username = tk.Entry(frame)
        self.username.pack()
        tk.Label(frame, text="密码").pack()
        self.password = tk.Entry(frame, show="*")
        self.password.pack()
        tk.Button(frame, text="登录", command=self.check_login).pack(pady=10)
        self.root.bind("<Return>", lambda event: self.check_login())

    def check_login(self):
        if self.username.get() == "admin" and self.password.get() == "zyp123":
            self.main_window()
        else:
            messagebox.showerror("错误", "用户名或密码错误")

    def main_window(self):
        for widget in self.root.winfo_children():
            widget.destroy()
        self.root.unbind("<Return>")
        frame = tk.Frame(self.root)
        frame.pack(pady=20)
        tk.Button(frame, text="添加会员", width=15, command=self.add_user_window).grid(row=0, column=0, padx=5)
        tk.Button(frame, text="充值", width=15, command=self.recharge_window).grid(row=0, column=1, padx=5)
        tk.Button(frame, text="消费", width=15, command=self.consume_window).grid(row=0, column=2, padx=5)
        tk.Button(frame, text="查询会员", width=15, command=self.search_user_window).grid(row=0, column=3, padx=5)
        tk.Button(frame, text="会员列表", width=15, command=self.view_users_window).grid(row=1, column=1, pady=10)
        tk.Button(frame, text="统计总表", width=15, command=self.total_summary).grid(row=1, column=2, pady=10)

    def center_window(self, win, width=300, height=200):
        screenwidth = win.winfo_screenwidth()
        screenheight = win.winfo_screenheight()
        x = int((screenwidth - width) / 2)
        y = int((screenheight - height) / 2)
        win.geometry(f"{width}x{height}+{x}+{y}")

    def add_user_window(self):
        win = tk.Toplevel(self.root)
        win.title("添加会员")
        self.center_window(win, 400, 300)
        tk.Label(win, text="姓名").pack()
        name = tk.Entry(win)
        name.pack()
        tk.Label(win, text="手机号").pack()
        phone = tk.Entry(win)
        phone.pack()
        def save():
            conn = sqlite3.connect("vip_data.db")
            cursor = conn.cursor()
            try:
                cursor.execute("INSERT INTO users (name, phone) VALUES (?, ?)", (name.get(), phone.get()))
                conn.commit()
                messagebox.showinfo("成功", "会员添加成功")
                win.destroy()
            except:
                messagebox.showerror("错误", "手机号已存在")
            conn.close()
        tk.Button(win, text="添加", command=save).pack(pady=10)

    def recharge_window(self):
        win = tk.Toplevel(self.root)
        win.title("充值")
        self.center_window(win, 400, 250)
        tk.Label(win, text="手机号尾号").pack()
        phone = tk.Entry(win)
        phone.pack()
        tk.Label(win, text="充值金额").pack()
        amount = tk.Entry(win)
        amount.pack()
        def recharge():
            conn = sqlite3.connect("vip_data.db")
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM users WHERE phone LIKE ?", ('%' + phone.get(),))
            user = cursor.fetchone()
            if user:
                new_balance = round(user[3] + float(amount.get()), 1)
                new_total = round(user[4] + float(amount.get()), 1)
                cursor.execute("UPDATE users SET balance = ?, total_recharge = ? WHERE phone = ?",
                               (new_balance, new_total, user[2]))
                cursor.execute("INSERT INTO records (phone, type, amount, date) VALUES (?, ?, ?, ?)",
                               (user[2], '充值', float(amount.get()), datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
                conn.commit()
                messagebox.showinfo("成功", "充值成功")
                win.destroy()
            else:
                messagebox.showerror("错误", "找不到手机号")
            conn.close()
        tk.Button(win, text="充值", command=recharge).pack(pady=10)

    def consume_window(self):
        win = tk.Toplevel(self.root)
        win.title("消费")
        self.center_window(win, 400, 250)
        tk.Label(win, text="手机号尾号").pack()
        phone = tk.Entry(win)
        phone.pack()
        tk.Label(win, text="消费金额").pack()
        amount = tk.Entry(win)
        amount.pack()
        def consume():
            conn = sqlite3.connect("vip_data.db")
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM users WHERE phone LIKE ?", ('%' + phone.get(),))
            user = cursor.fetchone()
            if user:
                if user[3] >= float(amount.get()):
                    new_balance = round(user[3] - float(amount.get()), 1)
                    cursor.execute("UPDATE users SET balance = ? WHERE phone = ?", (new_balance, user[2]))
                    cursor.execute("INSERT INTO records (phone, type, amount, date) VALUES (?, ?, ?, ?)",
                                   (user[2], '消费', float(amount.get()), datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
                    conn.commit()
                    messagebox.showinfo("成功", "消费成功")
                    win.destroy()
                else:
                    messagebox.showerror("错误", "余额不足")
            else:
                messagebox.showerror("错误", "找不到手机号")
            conn.close()
        tk.Button(win, text="消费", command=consume).pack(pady=10)

    def search_user_window(self):
        win = tk.Toplevel(self.root)
        win.title("查询会员")
        self.center_window(win, 400, 200)
        tk.Label(win, text="手机号尾号").pack()
        phone = tk.Entry(win)
        phone.pack()
        result = tk.Label(win, text="", font=("Arial", 12))
        result.pack()
        def search():
            conn = sqlite3.connect("vip_data.db")
            cursor = conn.cursor()
            cursor.execute("SELECT name, phone, balance FROM users WHERE phone LIKE ?", ('%' + phone.get(),))
            user = cursor.fetchone()
            if user:
                result.config(text=f"姓名: {user[0]}, 手机: {user[1]}, 金额: {user[2]}")
            else:
                result.config(text="未找到会员")
            conn.close()
        phone.bind("<Return>", lambda e: search())
        tk.Button(win, text="查询", command=search).pack(pady=10)

    def view_users_window(self):
        win = tk.Toplevel(self.root)
        win.title("会员列表")
        win.geometry("600x400")
        tree = ttk.Treeview(win, columns=("姓名", "手机号", "余额", "累计充值"), show='headings')
        tree.heading("姓名", text="姓名")
        tree.heading("手机号", text="手机号")
        tree.heading("余额", text="余额")
        tree.heading("累计充值", text="累计充值")
        tree.pack(fill=tk.BOTH, expand=True)
        conn = sqlite3.connect("vip_data.db")
        cursor = conn.cursor()
        cursor.execute("SELECT name, phone, balance, total_recharge FROM users")
        for row in cursor.fetchall():
            tree.insert("", tk.END, values=row)
        conn.close()

    def total_summary(self):
        conn = sqlite3.connect("vip_data.db")
        cursor = conn.cursor()
        cursor.execute("SELECT SUM(balance) FROM users")
        total = cursor.fetchone()[0]
        total = round(total if total else 0.0, 1)
        messagebox.showinfo("统计", f"现有会员总金额：{total} 元")
        conn.close()

if __name__ == "__main__":
    root = tk.Tk()
    app = VIPApp(root)
    root.mainloop()
